package com.sunny.ihealth.ui.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.sunny.ihealth.BaseActivity;
import com.sunny.ihealth.R;
import com.sunny.ihealth.data.BmobManager;
import com.sunny.ihealth.entity.bmob.UserInfo;
import com.sunny.ihealth.utils.MyTextUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import de.hdodenhof.circleimageview.CircleImageView;

public class EditUserInfoActivity extends BaseActivity implements View.OnClickListener {

    public static final int REQUEST_CODE_CAMERA = 1;
    public static final int REQUEST_CODE_GALLERY = 2;
    public static final int REQUEST_CODE_CROP = 3;

    private EditText etNickname;
    private EditText etSignature;
    private Button btnSave;
    private RadioGroup radioGroup;
    private CircleImageView ivHead;


    //头像图片
    private File currentPhotoFile;
    private File headFile;
    private String fileName;

    //从登陆界面进入，还是其他界面
    private boolean fromRegister = false;
    //从主页来
    private boolean fromMain = false;
    //注册用户首页查看
    private boolean fromMainUser = false;
    //是否更新了资料
    private boolean isUpdateInfo = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user_info);

        initViews();
        initData();
    }

    /**
     * 初始化资料
     */
    @Override
    public void initData() {
        Intent intent = getIntent();
        if (intent == null) {
            Toast.makeText(EditUserInfoActivity.this, "啊偶,未找到默认资料~", Toast.LENGTH_SHORT).show();
            btnSave.setEnabled(false);
            return;
        }
        UserInfo userInfo = (UserInfo) intent.getSerializableExtra("data");
        if (userInfo == null) {
            Toast.makeText(EditUserInfoActivity.this, "啊偶,未找到默认资料~", Toast.LENGTH_SHORT).show();
            btnSave.setEnabled(false);
            return;
        }

        fromRegister = intent.getBooleanExtra("fromRegister", false);
        fromMain = intent.getBooleanExtra("fromMain", false);
        fromMainUser = intent.getBooleanExtra("fromMainUser", false);

        if (userInfo.hasHead()) {
            Picasso.with(this).load(userInfo.getHeadFile().getUrl()).into(ivHead);
        }
        if (userInfo.getGender() == UserInfo.GENDER_MALE) {
            radioGroup.check(R.id.radioBtn_editUserInfo_male);
        } else {
            radioGroup.check(R.id.radioBtn_editUserInfo_female);
        }
        etNickname.setText(userInfo.getNickname());
        etSignature.setText(userInfo.getSignature());
    }


    @Override
    public void initViews() {
        setEnableBackIcon(true);
        setStatusBarColor();
        setToolbar("资料设置");

        TextInputLayout textInputLayoutNickname = (TextInputLayout) findViewById(R.id.textInputLayout_editUserInfo_nickname);
        TextInputLayout textInputLayoutSignature = (TextInputLayout) findViewById(R.id.textInputLayout_editUserInfo_signature);
        etNickname = textInputLayoutNickname.getEditText();
        etSignature = textInputLayoutSignature.getEditText();
        btnSave = (Button) findViewById(R.id.btn_editUserInfo_save);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup_editUserInfo);
        ivHead = (CircleImageView) findViewById(R.id.image_editUserInfo_head);
        ivHead.setOnClickListener(this);

        btnSave.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_editUserInfo_save:
                save();
                break;
            case R.id.image_editUserInfo_head:
                choosePicture();
                break;
        }
    }


    /**
     * 保存资料
     */
    private void save() {
        boolean gender;
        if (radioGroup.getCheckedRadioButtonId() == R.id.radioBtn_editUserInfo_male) {
            gender = UserInfo.GENDER_MALE;
        } else {
            gender = UserInfo.GENDER_FEMALE;
        }
        String nickname = etNickname.getText().toString().trim();
        String signature = etSignature.getText().toString().trim();
        if (!MyTextUtils.isLength(nickname, 1, 16)) {
            Toast.makeText(EditUserInfoActivity.this, "昵称格式有误,长度应在1-16位~", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(signature)) {
            signature = "这家伙很懒，什么都没留下...";
        }
        btnSave.setEnabled(false);


        //开始修改资料
        getBmob().updateUserInfo(nickname, signature, gender, new BmobManager.Action1<UserInfo>() {
            @Override
            public void onCompleted(UserInfo userInfo) {
                if (userInfo != null) {  //文字性资料修改成功
                    if (headFile != null && headFile.exists()) {  //头像是否存在，存在则更新头像
                        saveHeadFile();
                    } else {
                        getPreferencesHelper().setUserInfo(userInfo);
                        isUpdateInfo = true;

                        Toast.makeText(EditUserInfoActivity.this, "恭喜,资料更新成功~", Toast.LENGTH_SHORT).show();
                        btnSave.setEnabled(true);
                        finish();
                    }
                } else {
                    Toast.makeText(EditUserInfoActivity.this, "啊偶,资料更新失败~", Toast.LENGTH_SHORT).show();
                    btnSave.setEnabled(true);
                }
            }
        });
    }


    /**
     * 保存头像
     */
    private void saveHeadFile() {
        getBmob().updateUserHeadFile(headFile.getAbsolutePath(), new BmobManager.Action1<UserInfo>() {
            @Override
            public void onCompleted(UserInfo userInfo) {
                btnSave.setEnabled(true);
                if (userInfo != null) {  //头像修改成功
                    getPreferencesHelper().setUserInfo(userInfo);
                    isUpdateInfo = true;

                    Toast.makeText(EditUserInfoActivity.this, "恭喜,资料设置成功~", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(EditUserInfoActivity.this, "啊偶,头像上传失败~", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    /**
     * 选择头像
     */
    private void choosePicture() {
        new AlertDialog.Builder(EditUserInfoActivity.this)
                .setTitle("更换头像")
                .setItems(new String[]{"拍照", "从相册中选择"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent;
                        if (which == 0) { //拍照
                            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            //调用前置摄像头
                            intent.putExtra("camerasensortype", 1);
                            currentPhotoFile = new File(getPhotoFileName(false));
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentPhotoFile));
                            startActivityForResult(intent, REQUEST_CODE_CAMERA);
                        } else {  //从相册选择
                            intent = new Intent(Intent.ACTION_PICK);
                            intent.setType("image/*");
                            startActivityForResult(intent, REQUEST_CODE_GALLERY);
                        }
                    }
                })
                .create()
                .show();
    }


    /**
     * 生成图片文件名
     *
     * @param temp 是否是临时文件，临时文件为裁剪完的小头像，否则为拍摄的大照片
     * @return
     */
    private String getPhotoFileName(boolean temp) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        String filePath = "";
        if (temp) {   //保存裁剪文件
            filePath = Environment.getExternalStorageDirectory() + "/" + dateFormat.format(date) + ".jpg";
        } else {
            File cameraPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/");
            if (!cameraPath.exists()) {
                cameraPath.mkdirs();
            }
            filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/" + dateFormat.format(date) + ".jpg";
        }
        return filePath;
    }


    /**
     * 剪切图片
     *
     * @param uri
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别

        fileName = getPhotoFileName(true);
        if (headFile != null) {
            try {
                headFile.delete();
            } catch (Exception ignored) {
            }
        }
        headFile = new File(fileName); // 以时间为文件名
        intent.putExtra("output", Uri.fromFile(headFile)); // 保存剪切图片
        startActivityForResult(intent, REQUEST_CODE_CROP);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_GALLERY && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                crop(uri);
            }
        } else if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            crop(Uri.fromFile(currentPhotoFile));
        } else if (requestCode == REQUEST_CODE_CROP && resultCode == Activity.RESULT_OK) {
            Picasso.with(this).load(headFile).into(ivHead);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (headFile != null && headFile.exists()) {
                headFile.delete();
            }
        } catch (Exception ignored) {
        }
    }


    @Override
    public void finish() {
        //第一次进入注册的用户
        if (fromRegister && !fromMain) {
            Intent intent = new Intent(EditUserInfoActivity.this, MainActivity.class);
            startActivity(intent);
        }
        //更新首页数据
        if (fromMain || (fromMainUser && isUpdateInfo)) {
            getBaseApp().setUpdateState(true);
        }
        super.finish();
    }
}
